import {onMounted,reactive} from "vue";
import { nanoid } from 'nanoid'
import {timertype} from "../type/timertype";
import {useAlarmClock} from "../stores/AlarmClock";


export default function(){

    // 状态管理
    const store = useAlarmClock()
    // 闹钟列表
    let AlarmClockList:timertype[] = reactive([])
    /**
     * 获取闹钟列表
     * @constructor
     */
    const GetAlarmClockList = ()=>{
        let s = localStorage.getItem("alarmclocklist")
        if (s){
            let i = JSON.parse(s)
            AlarmClockList.push(...i)
            store.AlarmClockInfo = AlarmClockList
        }
    }
    /**
     * 添加一个闹钟
     * @param timer 时间
     * @constructor
     */
    const Add = (timer:string):void=>{
        if(timer){
            if (AlarmClockList.findIndex(x=>x.time===timer)<0){
                const d = {
                    id:nanoid(),
                    time:timer,
                    state:true
                }
                AlarmClockList.push(d)
                store.AlarmClockInfo = AlarmClockList
                localStorage.setItem("alarmclocklist",JSON.stringify(AlarmClockList))
            }
        }
    }
    /**
     * 修改
     * @param id 唯一标识符
     * @param timer 时间
     * @param state 状态
     * @constructor
     */
    const Update = (id:string,timer:string,state:boolean):void=>{
        let s = AlarmClockList.find(x=>x.id == id)
        if (s){
            if (timer)
                s.time = timer
            s.state = state
            store.AlarmClockInfo = AlarmClockList
            localStorage.setItem("alarmclocklist",JSON.stringify(AlarmClockList))
        }
    }
    /**
     * 删除
     * @param id 唯一标识符
     * @constructor
     */
    const Delete = (id:string):void=>{
        if (id){
            let s = AlarmClockList.findIndex(x=>x.id == id)
            if (s>=0){
                AlarmClockList.splice(s,1)
                store.AlarmClockInfo = AlarmClockList
                localStorage.setItem("alarmclocklist",JSON.stringify(AlarmClockList))
            }
        }
    }

    onMounted(():void=>{
        GetAlarmClockList()
    })

    return{
        AlarmClockList,
        Add,
        Update,
        Delete
    }
}